import axios from 'axios'
import utils from '@/utils/index'

const service = axios.create({
	baseURL: import.meta.env.VITE_APP_API_BASEURL,
	withCredentials: false,
	timeout: 300000
})

service.interceptors.request.use(
	(config) => {
		return config
	},
	(err) => {
		utils.msg('请求参数错误', 'error')
	}
)

service.interceptors.response.use(
	(response) => {
		const res = response.data

		if (res.code !== 200) {
			utils.msg(res.message || res.msg, 'error')
		}
		return res
	},
	(error) => {
		utils.msg(error.message || error.msg, 'error')
	}
)
// 接口请求
const request = function (url, params, config, method) {
	return new Promise((resolve, reject) => {
		service[method](url, params, Object.assign({}, config))
			.then(
				(response) => {
					resolve(response)
				},
				(err) => {
					err.Cancel ? console.log(err) : reject(err)
				}
			)
			.catch((err) => {
				reject(err)
			})
	})
}

export default {
	get: (url, params, config = {}) => request(url, params, config, 'get'),
	post: (url, params, config = {}) => request(url, params, config, 'post')
}
